import re
from datetime import date, datetime

from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
from django.db import models

from common.models import Common


class MyUserManager(BaseUserManager):
    """自定义User模型管理"""

    def create_user(self, username, password=None, **extra_fields):
        if not username:
            raise ValueError("Users must have a mobile number or an email address")

        # phone
        if len(username) == 11 and re.match("^(1[3456789]\d{9})$", username) is not None:
            user = self.model(
                username=username,
                phone=username,
                is_staff=False,
                is_active=True,
                is_superuser=False,
                **extra_fields
            )
        else:
            user = self.model(
                username=username,
                is_staff=False,
                is_active=True,
                is_superuser=False,
                **extra_fields
            )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, password, **extra_fields):
        user = self.create_user(username, password, **extra_fields)
        user.is_staff = True
        user.is_active = True
        user.is_superuser = True
        user.status = User.STATUS_VALID
        user.save(using=self._db)
        return user


class User(AbstractBaseUser, PermissionsMixin, Common):
    """自定义User模型"""
    username = models.CharField(u'用户登录名', max_length=128, default='', unique=True)
    phone = models.CharField(u'手机号码', max_length=20, default='', blank=True, db_index=True)
    email = models.EmailField(u'邮箱', max_length=255, blank=True, default='')
    gh_openid = models.CharField(u'openid', max_length=128, unique=True, null=True, blank=True, default=None)
    xcx_openid = models.CharField(u'小程序openid', max_length=128, unique=True, null=True, blank=True, default=None)
    unionid = models.CharField(u'unionid', max_length=128, default='', blank=True, db_index=True)

    logo = models.CharField(u'头像', max_length=1024, blank=True, default='')
    real_name = models.CharField(u'真实姓名', max_length=100, blank=True, default='')
    nick = models.CharField(u'昵称', max_length=100, default='')
    birthday = models.DateField(u'生日', default=date(1970, 1, 1))
    SEX_GIRL, SEX_BOY = 0, 1
    SEX_TYPE = ((SEX_BOY, '猛男'), (SEX_GIRL, '美女'))
    sex = models.IntegerField(u'性别', default=SEX_BOY, choices=SEX_TYPE)
    signature = models.CharField(u'签名', max_length=255, blank=True, default='')

    is_staff = models.BooleanField('staff status', default=False)
    is_active = models.BooleanField('active', default=True)
    deadline = models.DateTimeField(u'截止时间', default=datetime(1970, 1, 1))
    SELF_PUB, PAY_XIAODU, PAY_WX_SERVICE = 1, 2, 3
    PAY_TYPE = ((SELF_PUB, u'微信公众号支付'), (PAY_XIAODU, u'小嘟科技支付'), (PAY_WX_SERVICE, u'微信服务商子商户支付'),)
    pay_type = models.IntegerField(u'支付选择', choices=PAY_TYPE, default=PAY_XIAODU, blank=True)
    USERNAME_FIELD = 'username'
    objects = MyUserManager()

    def get_shop(self):
        if hasattr(self, 'shop_user'):
            return self.shop_user
        else:
            return None

    def get_address_list(self):
        if hasattr(self, 'receiver_set'):
            return self.receiver_set.all()
        else:
            return []

    class Meta:
        db_table = "user_info"
        verbose_name = '用户'
        ordering = ['-create_time']
